package com.hema.auction.base;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.apkfuns.logutils.LogUtils;
import com.iapppay.alpha.interfaces.callback.IPayResultCallback;
import com.iapppay.alpha.sdk.main.IAppPay;
import com.iapppay.alpha.sdk.main.IAppPayOrderUtils;
import com.reyun.sdk.TrackingIO;
import com.hema.auction.activity.MainActivity;
import com.hema.auction.event.PayResultEvent;
import com.hema.auction.event.TabIndexEvent;
import com.hema.auction.http.HttpTag;
import com.hema.auction.utils.Constant;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;

import static com.hema.auction.http.HttpTag.TAG_GET_PAY_STATUS;

/**
 * author by john
 * activity基类
 */
public class BaseRechargeActivity extends BaseActivity {
    protected String payType = "wechat_h5";
    protected WebView webview;
    protected boolean isPay;
    protected String orderSn;
    private int type;//支付类型 1充值  2我的竞拍支付 3不中包赔支付  4差价购买支付
    protected int payMethod = 401;
    private String transId;
    private float amount;

    /**
     * 支付宝------401
     * 微信支付----403
     * 银联支付----4
     * QQ钱包-----116
     */

    @SuppressLint("SetJavaScriptEnabled")
    protected void toPay(int type, String url) {
        this.type = type;
        if (webview == null)
            webview = new WebView(this);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        // 支持通过js打开新的窗口
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("weixin:") || url.startsWith("alipayqr:") || url.startsWith("alipays:")) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(false);
                    } catch (ActivityNotFoundException localActivityNotFoundException) {
                        showToastSafe("请检查是否安装客户端");
                        dismissProgressDialog();
                    }
                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }
        });
        webview.loadUrl(url);
        isPay = true;
    }
//
//    @Override
//    protected void onResume() {
//        super.onResume();
//        if (isPay)
//            getDefaultHandler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    HttpManager.getInstance(BaseRechargeActivity.this).getPayStatus(orderSn, BaseRechargeActivity.this);
//                }
//            }, 2000);
//        isPay = false;
//    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_GET_PAY_STATUS:
                try {
                    if (result.getInt("errcode") == 0) {
                        dismissProgressDialog();
                        showToastSafe("支付成功");
                        paySuccess();
                    }
                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToastSafe("获取订单结果异常");
                }
                break;
        }
    }

    protected void paySuccess() {

    }

    private void resultForword() {
        switch (type) {
            case 1://充值
                EventBus.getDefault().post(new TabIndexEvent(3));
                screenManager.popAllActivitys(MainActivity.class);
                break;
            case 2://我的竞拍付款
                setResult(RESULT_OK);
                EventBus.getDefault().post(new PayResultEvent(type));
                break;
            case 3://不中包赔付款
                setResult(RESULT_OK);
                break;
            case 4://差价购买付款
                setResult(RESULT_OK);
                EventBus.getDefault().post(new PayResultEvent(type));
                break;
        }
    }

    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        if (httpTag == TAG_GET_PAY_STATUS) {
            dismissProgressDialog();
        }
    }


    @Override
    protected void onError(HttpTag httpTag, Call call, IOException e) {
        super.onError(httpTag, call, e);
        dismissProgressDialog();
    }


    protected void startPay(int type, String transid,float amount) {
        this.type = type;
        this.transId = transid;
        this.amount = amount;
        String param = "transid=" + transid + "&appid=" + Constant.appid;
        IAppPay.startPay(this, param, payMethod, mIPayResultCallback);
        TrackingIO.setPaymentStart(transid, "alipay", "CNY", amount);
    }


    /**
     * 支付回调
     */
    protected IPayResultCallback mIPayResultCallback = new IPayResultCallback() {

        //@Override
        public void onPayResult(int resultCode, String signvalue, String resultInfo) {
            // TODO Auto-generated method stub

            switch (resultCode) {
                case IAppPay.PAY_SUCCESS:
                    boolean isPaySuccess = IAppPayOrderUtils.checkPayResult(signvalue, Constant.publicKey);
//                    if (isPaySuccess) {
//                        showToastSafe("支付成功");
//                    } else {
//                        showToastSafe("支付成功但验证签失败");
//                    }
                    showToastSafe("支付成功");
                    TrackingIO.setPayment(transId, "alipay", "CNY", amount);
                    paySuccess();
                    break;
                default:
                    showToastSafe(TextUtils.isEmpty(resultInfo) ? "unkown error" : resultInfo);
                    break;
            }
            LogUtils.d("requestCode:" + resultCode + ",signvalue:" + signvalue + ",resultInfo:" + resultInfo);
        }

    };


}
